/**
 * 之前list-subsidy-rule里的代码
 * 代码搬运工
 * 主要改了之前编辑的交互方式
 * 内部逻辑没有调整
 * */
import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import {
  Form,
  Row,
  Col,
  Radio,
  Switch,
  Checkbox,
  Modal,
  Button,
  Input,
  Select,
  Divider,
  Spin,
  message,
  Popconfirm,
  Icon,
  Popover,
  Tooltip
} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
import { setDefaultSetOfBook } from "actions/cache";
import SubsidyRuleService from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule-service';
import ItineraryField from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/itinerary-field';
import AllocationSubsidyExpense from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/allocation-subsidy-expense';
import "styles/setting/workflow-config/workflow-config.scss"
import ruleUtil from 'containers/expense-reimbursement-control/expense-standard/subsidy-rule/subsidy-rule-util';
import BraftEditor from 'braft-editor';
import ImageUpload from 'components/image-upload';
import UploadFile from 'components/upload';
import 'braft-editor/dist/braft.css';
import announcementService from 'containers/setting/announcement-information/announcement-information.service';
const options = [
  { label: messages('common.all')/*全部*/, value: 'ALL' },
  { label: messages('expense-8.key231')/*租户*/, value: 'TENANT' },
  { label: messages('expense-8.key2')/*公司*/, value: 'COMPANY' },
];
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15, offset: 1 },
};
class NewRuleComp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      typeBaseData: {},
      defaultRule: {},
      travelField: {},
      specialRule: {},
      itineraryField: {},
      subsidyScopeValue: {
        range: 'ALL',
        value: []
      }
    }
  }

  componentDidMount() {
    const { typeBaseData, defaultRule, travelField, specialRule, itineraryField } = this.props.params;
    this.setState({
      typeBaseData, defaultRule, travelField, specialRule, itineraryField
    }, this.initSubsidyScope)
  }

  initSubsidyScope = () => {
    const { typeBaseData } = this.state;
    let subsidyScopeValue = {
      range: 'ALL',
      value: []
    };
    if (typeBaseData.subsidySelection && typeBaseData.subsidySelectionExpenseTypeOIDs && typeBaseData.subsidySelectionExpenseTypeOIDs.length) {
      subsidyScopeValue.range = 'PARTIAL';
      let subsidyExpenseList = typeBaseData.subsidySelectionExpenseTypeOIDs;
      subsidyExpenseList.forEach(expense => {
        subsidyScopeValue.value.push({
          expenseTypeOID: expense.expenseTypeOID,
          expenseTypeName: expense.name
        });
      });
    }
    this.setState({subsidyScopeValue});
  };

  //保存头部规则生成器的基础设置按钮回调（保存按钮回调）
  saveTypeBaseSet = (e) => {
    e.stopPropagation();
    const { typeBaseData, defaultRule, itineraryField, subsidyScopeValue } = this.state;
    let copyTypeBaseData = JSON.parse(JSON.stringify(typeBaseData));
    let changeStr = "";
    let isCityCheck = true;
    defaultRule.dimensionDetails && defaultRule.dimensionDetails.map((item, index) => {
      if (item.code === 'ALLOWANCE_CITY') {
        isCityCheck = item.selected;
      }
    });
    //保存头部规则生成器的基础设置前校验差补城市,行程值列表不可与自动差补同时开启
    let isHasItineraryField = itineraryField && itineraryField.itineraryFieldList && itineraryField.itineraryFieldList.length;
    if ((isCityCheck || isHasItineraryField) && copyTypeBaseData.applicationAutoSubsidy) {
      message.error(messages('expense-8.key232')/*申请单自动差补功能不可与默认规则-差补城市、行程字段同时启用*/);
      return;
    }
    if (copyTypeBaseData.subsidySelection && subsidyScopeValue.range === 'PARTIAL' && !subsidyScopeValue.value.length) {
      message.error(messages('expense-8.key371')/*请选择差补类型*/);
      return;
    }
    if (copyTypeBaseData.subsidySelection && subsidyScopeValue.range === 'PARTIAL') {
      let subsidyExpenseList = [];
      subsidyScopeValue.value.forEach(expense => {
        subsidyExpenseList.push({
          expenseTypeOID: expense.expenseTypeOID,
          name: expense.expenseTypeName
        });
      });
      copyTypeBaseData.subsidySelectionExpenseTypeOIDs = subsidyExpenseList;
    } else {
      copyTypeBaseData.subsidySelectionExpenseTypeOIDs = null;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (copyTypeBaseData.withTips) {
          copyTypeBaseData.tips = values.tips ? values.tips : "";
        } else {
          copyTypeBaseData.tips = '';
        }
        copyTypeBaseData.dimensionTypes.map(item => {
          item.dimensionDetails.map(detail => {
            if (values.hasOwnProperty([detail.code])) {
              if (detail.selected !== values[detail.code]) {
                changeStr = changeStr + ruleUtil.changeByCode(detail.code) + ' , ';
              }
              detail.selected = values[detail.code];
            }
            //校验默认规则中差补城市的勾选是否改变
            if (detail.code === 'ALLOWANCE_CITY' && isCityCheck !== detail.selected) {
              changeStr = changeStr + ruleUtil.changeByCode(detail.code) + ' , ';
              detail.selected = isCityCheck;
            }
          })
          if (item.formFieldDetails) {
            item.formFieldDetails.map(detail => {
              if (values.hasOwnProperty([detail.fieldOID])) {
                if (detail.selected !== values[detail.fieldOID]) {
                  changeStr = changeStr + detail.name + ' , ';
                }
                detail.selected = values[detail.fieldOID];
              }
            })
          }
          //处理行程值列表
          if (item.name === 'ITINERARY_FIELDS') {
            changeStr += ruleUtil.judgeIsChangeCust(item.itineraryFieldList, itineraryField.itineraryFieldList);
            item.itineraryFieldList = itineraryField.itineraryFieldList;
          }
        });

        this.processSaveStep1(copyTypeBaseData, changeStr);
      }
    })
  };

  extractContents = (nodes) => {
    let content = '';
    if (nodes.length === 0) {
      return '';
    }
    (nodes || []).forEach(node => {
      //只处理文本类型节点
      if (node.nodeType === Node.TEXT_NODE) {
        content += node.textContent || node.nodeValue;
      }
      if (node.nodeType === Node.ELEMENT_NODE) {
        content += this.extractContents(node.childNodes);
      }
    });
    return content;
  };

  //保存头部规则生成器的基础设置
  toSave = (typeBaseData) => {
    let htmlDiv = document.createElement('div');
    htmlDiv.innerHTML = typeBaseData.tips;
    typeBaseData.tips =  typeBaseData.tips.replace(/<p><\/p>/gi,"</br>")
    if (typeBaseData.withTips && !this.extractContents(htmlDiv.childNodes)) {
      message.error(messages('expense-8.key233')/*请填写提示内容*/);
      return;
    }
    this.setState({ request: true });
    SubsidyRuleService.saveSubsidyHead(typeBaseData).then(res => {
      message.success(messages('expense-8.key21')/*保存成功*/);
      this.setState({ request: false });
      this.props.close(true);
    }).catch(err => {
      this.setState({ request: false });
      message.error(err.response.data.message);
    })
  };

  //保存头部规则生成器的基础设置
  processSaveStep1 = (copyTypeBaseData, changeStr) => {
    const { isInitBaseData } = this.state;
    if (!isInitBaseData || !changeStr) {
      this.toSave(copyTypeBaseData);
    } else {
      changeStr = changeStr.substr(0, changeStr.length - 2);
      Modal.confirm({
        title: messages('expense-8.key234')/*修改后将影响当前规则，确认保存?*/,
        content: changeStr,
        onOk: () => {
          this.toSave(copyTypeBaseData);
        },
        onCancel: () => {},
      });
    }
  };

  isOpenTips = (isOpen) => {
    const { typeBaseData } = this.state;
    typeBaseData.withTips = isOpen;
    this.setState({ typeBaseData });
  };

  //规则生成器的基础数据编辑取消按钮回调
  //isRefresh是否还原数据，保存后不用，取消后需要还原数据
  cancelTypeEdit = () => {
    this.props.close();
  };


  //富文本中上传图片
  handleImageUpload = (param) => {
    const formData = new FormData();
    formData.append('attachmentType', 'CARROUSEL_IMAGES');
    formData.append('file', param.file);
    announcementService.handleImageUpload(formData).then(res => {
      param.success({url: res.data.fileURL})
    }).catch(e => {
      param.error();
      message.error(`${messages('expense-8.key235')/*图片上传失败*/}，${e.response.data.message}`)
    })
  };


  //默认规则切换checkbox
  handleCheckbox = (e) => {
    const { defaultRule } = this.state;
    defaultRule.dimensionDetails && defaultRule.dimensionDetails.map((item, index) => {
      if (item.code === 'ALLOWANCE_CITY') {
        item.selected = e.target.checked;
      }
    });
    this.setState({ defaultRule });
  };

  updateValueRuleList = (valueRuleList) => {
    const { itineraryField } = this.state;
    itineraryField.itineraryFieldList = valueRuleList;
    this.setState({ itineraryField });
  };

  handleSelectSwitch = (value, key) => {
    const { typeBaseData } = this.state;
    typeBaseData[key] = value;
    this.setState({ typeBaseData });
  };

  handleStatusChange = (value, key) => {
    this.setState({
      [key]: value
    });
  };

  render() {
    const linkStyle = {
      fontSize: '12px',
      color: '#848C95'
    };
    const layout = {
      labelCol: {span: 6},
      wrapperCol: {span: 18}
    };
    const controls = [
      'undo', 'redo', 'split', 'text-align', 'font-size', 'font-family', 'line-height', 'text-color',
      'bold', 'italic', 'underline', 'strike-through', 'superscript',
      'subscript', 'split', 'headings', 'list_ul', 'list_ol', 'image',
    ];
    const { typeBaseData, defaultRule, travelField, specialRule, itineraryField, request, subsidyScopeValue } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { levelCode, levelOrgId } = this.props.params;
    return (
      <div className='workflow-config subsidy-rules'>
        <Form className="new-form subsidy-type-list">
          <FormItem {...layout} label={messages('expense-8.key236')/*默认规则*/}>
            <div className="title-edit">
              {defaultRule.dimensionDetails && defaultRule.dimensionDetails.map((item, index) => {
                return (
                  <Checkbox key={item.code} disabled={item.code !== 'ALLOWANCE_CITY'} checked={item.selected}
                            onChange={this.handleCheckbox}>
                    {ruleUtil.changeByCode(item.code, 'edit')}
                  </Checkbox>
                )
              })}
            </div>
          </FormItem>

          <FormItem {...layout} label={messages('expense-8.key206')/*申请单字段*/}>
            {travelField.dimensionDetails && travelField.dimensionDetails.map((item, index) => {
              return (
                <div style={{float: 'left', marginRight: 32}}>
                  {getFieldDecorator(item.code, {
                    valuePropName: 'checked',
                    initialValue: item.selected
                  })(
                    <Checkbox key={item.code}>{ruleUtil.changeByCode(item.code, 'edit')}</Checkbox>
                  )}
                </div>
              )
            })}

            {travelField.formFieldDetails && travelField.formFieldDetails.map(item => {
              return (
                <div style={{float: 'left', marginRight: 32}}>
                  {getFieldDecorator(item.fieldOID, {
                    valuePropName: 'checked',
                    initialValue: item.selected
                  })(
                    <Checkbox key={item.fieldOID}>{item.name}</Checkbox>
                  )}
                </div>
              )
            })}
          </FormItem>

          <FormItem {...layout} label={messages('expense-8.key207')/*行程字段*/}>
            <div className="title-edit">
              <ItineraryField
                valueList={itineraryField ? (itineraryField.itineraryFieldList || []) : []}
                onChange={this.updateValueRuleList}
                levelOrgId={levelOrgId}
                levelCode={levelCode}
              />
            </div>
          </FormItem>

         <FormItem {...layout} label={messages('expense-8.key208')/*特殊控制*/}>
            <div className="special-item">
              {specialRule.dimensionDetails && specialRule.dimensionDetails.map((item, index) => {
                return (
                  <div>
                    {getFieldDecorator(item.code, {
                      valuePropName: 'checked',
                      initialValue: item.selected
                    })(
                      <Checkbox key={item.code}>{ruleUtil.changeByCode(item.code, 'edit')}</Checkbox>
                    )}
                  </div>
                )
              })}
              <div style={linkStyle}>{messages('expense-8.key223')/*前往*/}<a href="/main/setting/work-calendar" style={{color: "#4B8DFF"}}>{messages('expense-8.key372')/*【工作日历】*/}</a>{messages('expense-8.key373')/*，查看或编辑日期属性*/}</div>
            </div>
          </FormItem>

          <FormItem {...layout} label={messages('expense-8.key116')/*提示内容*/}>
              <div style={{ display: 'flex' }}>
                <Switch checked={typeBaseData.withTips} onChange={this.isOpenTips}></Switch>
                <span style={{ color: '#ccc' }}>&nbsp;{messages('expense-8.key237')/*用于在添加差补页面提醒员工相关政策，关闭后不显示*/}</span>
              </div>
              {typeBaseData.withTips &&
                <div style={{ margin: '8px 0'}}>
                  {getFieldDecorator('tips', {
                    initialValue: typeBaseData.tips
                  })(
                    <BraftEditor height={200}
                                controls={controls}
                                language={this.props.language.locale}
                                contentFormat="html"
                                initialContent={typeBaseData.tips}
                                media={{
                                  image: true,
                                  video: false,
                                  audio: false,
                                  externalMedias: {
                                    image: false,
                                    video: false,
                                    audio: false
                                  },
                                  uploadFn: this.handleImageUpload
                                }}
                                ref={instance => this.editorInstance = instance}/>
                  )}
                </div>
              }

          </FormItem>

          <FormItem {...layout} label={messages('expense-8.key370')/*差补类型默认勾选*/}>
            <Switch checked={typeBaseData.subsidySelection}
                    onChange={value => this.handleSelectSwitch(value, 'subsidySelection')}/>
          </FormItem>

          {typeBaseData.subsidySelection && (
            <FormItem {...layout} label={messages('expense-8.key374')/*选择差补类型*/}>
              <div className="allocation-subsidy-expense">
                <AllocationSubsidyExpense
                  parser={value => ({range: value.range, value: value.value || []})}
                  value={subsidyScopeValue}
                  onChange={value => this.handleStatusChange(value, 'subsidyScopeValue')}
                  componentProps={{
                    'PARTIAL': {
                      params: {
                        formOID: this.props.params.formOID
                      }
                    }
                  }}
                />
              </div>
            </FormItem>
          )}

          <FormItem {...layout} label={<span>{messages('expense-8.key210')/*申请单自动差补*/}&nbsp;
                                        <Popover
                                          content={messages('expense-8.key238')/*开启申请单自动差补功能，将在填写申请单时，自动根据参与人、往返日期计算和保存差补行程；不可与默认规则-差补城市、行程字段同时启用。*/}
                                          placement="top"
                                        >
                                          <Icon type="info-circle-o" className='font-description' style={{fontSize: 14}} />
                                        </Popover></span>}
          >
            <Switch checked={typeBaseData.applicationAutoSubsidy}
                    onChange={value => this.handleSelectSwitch(value, 'applicationAutoSubsidy')}/>
          </FormItem>

          <div className="slide-footer">
            <Button type="primary" loading={request}
                    onClick={this.saveTypeBaseSet}>{messages('common.save')/*保存*/}</Button>
            <Button style={{ marginLeft: 12 }}
                    onClick={() => {this.cancelTypeEdit(true)}}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

NewRuleComp.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode,
    language: state.main.language,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}

const wrappedNewRule = Form.create()(NewRuleComp);

export default connect(mapStateToProps)(wrappedNewRule)
